#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
#include<vector>
#include<set>
using namespace std;
  struct ListNode {
      int val;
      ListNode *next;
      ListNode(int x) : val(x), next(NULL) {}
  };
 
class Solution {
public:
    ListNode* detectCycle(ListNode* head) {
        ListNode* cur = head;
        set<ListNode*> as;
        while (cur)
        {
            if (as.insert(cur).second == false)
            {
                return cur;
            }
            cur = cur->next;
        }
        return nullptr;
    }
};